<?php

namespace JsonLowCode\Table;

use JsonLowCode\UI\AppLink;
use JsonLowCode\Table;

class Action extends BaseAction
{
    protected string $path = "";

    protected array $allowFields = ['id'];
    protected array $query = [];
    protected array $params = [];

    public function __construct(string $text = "", string $path = "", Table $table = null)
    {
        parent::__construct($table);
        $this->element = new AppLink($text);
        $this->path = $path;

    }

    /**
     *
     * @param array $fields
     * @return $this
     */
    public function allowField(array $fields): static
    {
        $this->allowFields = array_merge($this->allowFields,$fields);
        return $this;
    }

    /**
     * @param array $query
     * @return $this
     */
    public function query(array $query = []): static
    {
        $this->query = array_merge($this->query,$query);
        return $this;
    }

    protected function booted(): void
    {
        $query = $this->query;
        foreach ($this->allowFields as $field){
            $query[$field] = JSExpression($this->rowDataField.".".$field);
        }
        $toObject = [
            'path'=>$this->path,
        ];
        if ($query){
            $toObject['query'] = $query;
        }
        $this->element->to($toObject);
    }
}
